package com.ruoyi.system.service.aggregation.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.system.domain.aggregation.Account;
import com.ruoyi.system.domain.aggregation.Order;
import com.ruoyi.system.domain.aggregation.Point;
import com.ruoyi.system.domain.aggregation.Proportion;
import com.ruoyi.system.domain.aggregation.User;
import com.ruoyi.system.mapper.aggregation.AccountMapper;
import com.ruoyi.system.mapper.aggregation.PointMapper;
import com.ruoyi.system.mapper.aggregation.ProportionMapper;
import com.ruoyi.system.mapper.aggregation.UserMapper;
import com.ruoyi.system.service.aggregation.ICommissionService;

/**
 * 分佣计算Service实现
 * 
 * @author ruoyi
 * @date 2025-01-01
 */
@Service
public class CommissionServiceImpl implements ICommissionService 
{
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AccountMapper accountMapper;

    @Autowired
    private PointMapper pointMapper;

    @Autowired
    private ProportionMapper proportionMapper;

    private static final int COMMISSION_TYPE_AD = 1; // 广告分佣
    private static final int COMMISSION_TYPE_ORDER = 2; // 异业联盟分佣

    /**
     * 异业联盟分佣（订单支付后）
     * 分佣对象：C端用户、商家、业务员、区域代理、总公司
     */
    @Override
    @Transactional
    public void calculateOrderCommission(Order order)
    {
        // 获取C端用户信息
        User cUser = userMapper.selectUserById(order.getCUserId());
        if (cUser == null) return;

        // 获取商家信息
        User merchant = userMapper.selectUserById(order.getMerchantId());
        if (merchant == null) return;

        // 订单金额（人民币部分）
        Long payAmount = order.getPayAmount();
        if (payAmount == null || payAmount <= 0) return;

        // 1. C端用户分佣
        Proportion cUserProp = proportionMapper.selectProportionByTypeAndRole(COMMISSION_TYPE_ORDER, 1);
        if (cUserProp != null)
        {
            distributeCommission(cUser.getId(), 1, payAmount, cUserProp.getProportion(), null);
        }

        // 2. 商家分佣
        Proportion merchantProp = proportionMapper.selectProportionByTypeAndRole(COMMISSION_TYPE_ORDER, 3);
        if (merchantProp != null)
        {
            distributeCommission(merchant.getId(), 3, payAmount, merchantProp.getProportion(), null);
        }

        // 3. 业务员分佣（如果商家有绑定业务员）
        if (merchant.getSalesmanNo() != null)
        {
            User salesman = userMapper.selectUserByPhone(merchant.getSalesmanNo());
            if (salesman != null)
            {
                Proportion salesmanProp = proportionMapper.selectProportionByTypeAndRole(COMMISSION_TYPE_ORDER, 2);
                if (salesmanProp != null)
                {
                    distributeCommission(salesman.getId(), 2, payAmount, salesmanProp.getProportion(), null);
                }
            }
        }

        // 4. 区域代理分佣（如果商家有绑定区域代理）
        if (merchant.getRegionId() != null)
        {
            User region = userMapper.selectUserById(merchant.getRegionId());
            if (region != null)
            {
                Proportion regionProp = proportionMapper.selectProportionByTypeAndRole(COMMISSION_TYPE_ORDER, 4);
                if (regionProp != null)
                {
                    distributeCommission(region.getId(), 4, payAmount, regionProp.getProportion(), null);
                }
            }
        }

        // 5. 总公司分佣
        Proportion companyProp = proportionMapper.selectProportionByTypeAndRole(COMMISSION_TYPE_ORDER, 5);
        if (companyProp != null)
        {
            // 查找总公司用户（type=5）
            User company = new User();
            company.setType(5);
            List<User> companyList = userMapper.selectUserList(company);
            if (!companyList.isEmpty())
            {
                distributeCommission(companyList.get(0).getId(), 5, payAmount, companyProp.getProportion(), null);
            }
        }
    }

    /**
     * 广告分佣（用户看广告后）
     * 分佣对象：C端用户、商家（如果绑定）、业务员、区域代理、总公司
     */
    @Override
    @Transactional
    public void calculateAdCommission(Long userId, Long rewardAmount, String platform)
    {
        User cUser = userMapper.selectUserById(userId);
        if (cUser == null) return;

        // 1. C端用户分佣
        Proportion cUserProp = proportionMapper.selectProportionByTypeAndRole(COMMISSION_TYPE_AD, 1);
        if (cUserProp != null)
        {
            distributeCommission(userId, 1, rewardAmount, cUserProp.getProportion(), platform);
        }

        // 2. 如果C端用户绑定了商家，给商家分佣
        if (cUser.getMerchantId() != null)
        {
            User merchant = userMapper.selectUserById(cUser.getMerchantId());
            if (merchant != null)
            {
                Proportion merchantProp = proportionMapper.selectProportionByTypeAndRole(COMMISSION_TYPE_AD, 3);
                if (merchantProp != null)
                {
                    distributeCommission(merchant.getId(), 3, rewardAmount, merchantProp.getProportion(), platform);
                }

                // 3. 业务员分佣
                if (merchant.getSalesmanNo() != null)
                {
                    User salesman = userMapper.selectUserByPhone(merchant.getSalesmanNo());
                    if (salesman != null)
                    {
                        Proportion salesmanProp = proportionMapper.selectProportionByTypeAndRole(COMMISSION_TYPE_AD, 2);
                        if (salesmanProp != null)
                        {
                            distributeCommission(salesman.getId(), 2, rewardAmount, salesmanProp.getProportion(), platform);
                        }
                    }
                }

                // 4. 区域代理分佣
                if (merchant.getRegionId() != null)
                {
                    User region = userMapper.selectUserById(merchant.getRegionId());
                    if (region != null)
                    {
                        Proportion regionProp = proportionMapper.selectProportionByTypeAndRole(COMMISSION_TYPE_AD, 4);
                        if (regionProp != null)
                        {
                            distributeCommission(region.getId(), 4, rewardAmount, regionProp.getProportion(), platform);
                        }
                    }
                }
            }
        }

        // 5. 总公司分佣
        Proportion companyProp = proportionMapper.selectProportionByTypeAndRole(COMMISSION_TYPE_AD, 5);
        if (companyProp != null)
        {
            User company = new User();
            company.setType(5);
            List<User> companyList = userMapper.selectUserList(company);
            if (!companyList.isEmpty())
            {
                distributeCommission(companyList.get(0).getId(), 5, rewardAmount, companyProp.getProportion(), platform);
            }
        }
    }

    /**
     * 分配佣金
     * @param userId 用户ID
     * @param userType 用户类型
     * @param amount 总金额（分）
     * @param proportion 分成比例
     * @param platform 平台类型（广告平台）
     */
    private void distributeCommission(Long userId, Integer userType, Long amount, 
                                     BigDecimal proportion, String platform)
    {
        // 计算分佣金额
        BigDecimal commissionAmount = new BigDecimal(amount)
            .multiply(proportion)
            .setScale(0, RoundingMode.HALF_UP);

        // 更新账户余额
        Account account = accountMapper.selectAccountByUserId(userId);
        if (account != null)
        {
            // 总余额增加
            account.setTotalBalance(account.getTotalBalance() + commissionAmount.longValue());
            // 积分余额增加（100积分=1元，所以积分=金额/100*100=金额分）
            BigDecimal pointIncrease = commissionAmount.divide(new BigDecimal(100), 2, RoundingMode.HALF_UP);
            account.setPointBalance(account.getPointBalance().add(pointIncrease));
            account.setUpdateTime(new Date());
            accountMapper.updateAccount(account);
        }

        // 记录积分明细
        Point point = new Point();
        point.setUserId(userId);
        point.setType(userType);
        point.setPoint(commissionAmount.divide(new BigDecimal(100), 2, RoundingMode.HALF_UP));
        point.setIncrease("1"); // 增加
        point.setPlatform(platform);
        point.setDeleted(0);
        point.setCreateTime(new Date());
        pointMapper.insertPoint(point);
    }
}

